package cn.zxf.note.security.platform;

import cn.zxf.note.common.web.RestUtils;
import cn.zxf.note.user.platform.PlatformEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * Created by zengxf on 2020/3/25.
 */
@Slf4j
@Component
public class WeappLoginService extends AbstractPlatformLoginService {

    @Value("${platform.weapp.appId}")
    private String appId;
    @Value("${platform.weapp.appSecret}")
    private String appSecret;

    public WeappLoginService() {
        super(PlatformEnum.WEAPP);
    }

    @Override
    public LoginResult login(LoginRequest request) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid={appid}&" +
                "secret={secret}&" +
                "js_code={js_code}&" +
                "grant_type={grant_type}";
        Map<String, Object> params = Map.of(
                "appid", this.appId,
                "secret", this.appSecret,
                "js_code", request.getCode(),
                "grant_type", "authorization_code"
        );
        Map res = RestUtils.get(url, Map.class, params);
        log.info("login-res: {}", res);

        Object errCode = res.get("errcode");
        if (errCode != null && !Objects.equals("0", errCode)) {
            return new LoginResult()
                    .setSign(LoginResult.SIGN_ERROR)
                    .setMessage("请求出错：" + res.get("errmsg").toString());
        }

        String openId = res.get("openid").toString();
        LoginResult result = super.login(openId);
        return result;
    }

}
